package models

import "time"

func (db *DbWrapper) GetFlowerConfigByid(id int) *FlowerConfigs {
	u1 := new(FlowerConfigs)
	db.DbInstance.Where("id=?", id).First(&u1)
	return u1
}

func (db *DbWrapper) GetFlowerConfig(quality int, star int) []*FlowerConfigs {
	var fcs []*FlowerConfigs
	db.DbInstance.Where("(type=0 and quality=?) or (type=1 and quality=? and plantamount<=?)", quality, quality, star).Find(&fcs)

	return fcs
}

func (db *DbWrapper) GetFlowerConfigWithoutStar(quality int) []*FlowerConfigs {
	var fcs []*FlowerConfigs
	db.DbInstance.Where("type=0 and quality=?", quality).Find(&fcs)

	return fcs
}

func (db *DbWrapper) CreateLootedSeed(uid int, fid int, amount int) int64 {
	userf := &UserFlower{
		Uid:     uid,
		Fid:     fid,
		State:   0,
		Settime: time.Now(),
		Waterid: 0,
		Amount:  amount,
	}
	db.DbInstance.Create(&userf)
	return int64(userf.Id)
}

func (db *DbWrapper) GetUserFlowers(uid int) []*UserFlowersResult {
	var datas []*UserFlowersResult
	db.DbInstance.Model(&UserFlower{}).Select("user_flowers.*, users.nname as watername,users.headicon as waterheadicon,users.headurl as waterheadurl").Joins("left join users on user_flowers.waterid = users.id where user_flowers.uid=?", uid).Scan(&datas)
	return datas
}

func (db *DbWrapper) GetFlower(id int) *UserFlower {
	u1 := new(UserFlower)
	db.DbInstance.Where("id=?", id).First(&u1)
	return u1
}

func (db *DbWrapper) GetFlowerDoneByOwner(id int) *UserFlower {
	u1 := new(UserFlower)
	db.DbInstance.Where("id=? and state=1 ", id).First(&u1)
	return u1
}

func (db *DbWrapper) WaterFlowerStage(id int, state int) int64 {
	result := db.DbInstance.Model(&UserFlower{}).Where("id = ?", id).Updates(map[string]interface{}{"state": state})
	return result.RowsAffected
}

func (db *DbWrapper) WaterFlowerStageAndWaterBy(id int, state int, uid int) int64 {
	result := db.DbInstance.Model(&UserFlower{}).Where("id = ?", id).Updates(map[string]interface{}{"state": state, "waterid": uid})
	return result.RowsAffected
}

func (db *DbWrapper) DeleteFlowerStage(id int, state int) {
	db.DbInstance.Where("id=? and state>0", id).Delete(&UserFlower{})
}

func (db *DbWrapper) WaterFlowerTimer() int64 {
	result := db.DbInstance.
		Model(&UserFlower{}).
		Where("DATE_ADD(settime, INTERVAL ? second) <= NOW() and state=0", db.DbConfigs.Gp.Autowatertime).
		Updates(map[string]interface{}{"state": 1})
	return result.RowsAffected
}

func (db *DbWrapper) GetFlowersByIds(ids []int) []*UserFlower {
	var datas []*UserFlower
	db.DbInstance.Where("uid in ? and state=0", ids).Find(&datas)
	return datas
}

func (db *DbWrapper) GetFlowersExcludeIds(ids []int, limit int) []*UserFlower {
	var datas []*UserFlower
	db.DbInstance.Where("uid not in ? and state=0", ids).Find(&datas).Limit(limit)
	return datas
}
